package com.aiyige.page.launch;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaCodec;
import android.media.MediaExtractor;
import android.media.MediaFormat;
import android.media.MediaMetadataRetriever;
import android.media.MediaMuxer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ApiUrls;
import com.aiyige.configs.MyConfig;
import com.aiyige.page.my.buy.MyBuyPage;
import com.aiyige.page.my.download.util.DownloadUtil;
import com.aiyige.page.my.favorite.MyFavoritePage;
import com.aiyige.page.my.order.myOrder.MyOrdersPage;
import com.aiyige.page.my.order.sellerOrder.OrderManagerPage;
import com.aiyige.page.my.view.MyViewsPage;
import com.aiyige.page.pay.util.PayUtil;
import com.aiyige.page.publish.majorcourse.model.MajorCourseFormModel;
import com.aiyige.page.test.TestQNPlayerPage;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.TimeUtils;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.dialog.LoadingDialog;
import com.aiyige.utils.ffmpeg.TranscoderUtils;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.tencent.mm.opensdk.modelbase.BaseResp;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import timber.log.Timber;

@Route(path = ARouterConfig.DebugPage)
public class DebugPage extends BaseActivity {

    @BindView(R.id.downloadGoodsIdEt)
    EditText downloadGoodsIdEt;
    @BindView(R.id.downloadEnterTypeEt)
    EditText downloadEnterTypeEt;
    BroadcastReceiver receiver;
    IntentFilter intentFilter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_debug);
        ButterKnife.bind(this);
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                try {
                    switch (intent.getAction()) {
                        case PayUtil.ACTION_WECHAT_PAY_RESULT: {
                            int resultCode = intent.getIntExtra(PayUtil.EXTRA_KEY_WECHAT_PAY_RESULT_CODE, BaseResp.ErrCode.ERR_SENT_FAILED);
                            String resultMsg = intent.getStringExtra(PayUtil.EXTRA_KEY_WECHAT_PAY_RESULT_MSG);
                            break;
                        }
                        case PayUtil.ACTION_ALIPAY_RESULT: {
                            String json = intent.getStringExtra(PayUtil.EXTRA_KEY_ALIPAY_RESULT);
                            JSONObject result = JSON.parseObject(json);

                            break;
                        }
                        default: {

                            break;
                        }

                    }
                } catch (Exception e) {
                    ToastX.show(e.getMessage());
                }
            }
        };
        intentFilter = new IntentFilter();
        intentFilter.addAction(PayUtil.ACTION_WECHAT_PAY_RESULT);
        registerReceiver(receiver, intentFilter);
    }

    @Override
    protected void onDestroy() {
        try {
            unregisterReceiver(receiver);
        } catch (Exception e) {

        }
        super.onDestroy();
    }

    @OnClick({R.id.loadingDialogTest, R.id.wechatPay, R.id.publishMajorCourseFormBtn, R.id.publishMajorCourseDescBtn, R.id.downloadBtn, R.id.myDownloadPage, R.id.myUserPage, R.id.messageCenterPage, R.id.merchandiseManagementPage, R.id.publishNormalVideoPage, R.id.publishInfoPage, R.id.publishPhotoPage, R.id.publishLearnVideoPage, R.id.guaranteePage, R.id.logoutBtn, R.id.editUserBannerPage, R.id.selectRegionPage, R.id.selectInterestPage, R.id.loginPage, R.id.findPasswordPage, R.id.registerPage, R.id.resetPasswordPage, R.id.selectCountryPage, R.id.mainPage, R.id.userPage, R.id.launchPage, R.id.editUserInfoPage, R.id.editUserNamePage, R.id.select_video, R.id.order_manager, R.id.my_orders, R.id.test_tra, R.id.myFavorite, R.id.myView, R.id.myBuy})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.logoutBtn:
                AccountUtil.clearCurrentUser();
                break;
            case R.id.loginPage:
                ARouter.getInstance().build(ARouterConfig.LoginPage).navigation();
                break;
            case R.id.findPasswordPage:
                ARouter.getInstance().build(ARouterConfig.FindPasswordPage).navigation();
                break;
            case R.id.registerPage:
                ARouter.getInstance().build(ARouterConfig.RegisterPage).navigation();
                break;
            case R.id.resetPasswordPage:
                ARouter.getInstance().build(ARouterConfig.ResetPasswordPage).navigation();
                break;
            case R.id.selectCountryPage:
                ARouter.getInstance().build(ARouterConfig.SelectCountryPage).navigation();
                break;
            case R.id.mainPage:
                ARouter.getInstance().build(ARouterConfig.MainPage).navigation();
                break;
            case R.id.userPage:
                ARouter.getInstance().build(ARouterConfig.UserPage).navigation();
                break;
            case R.id.launchPage:
                ARouter.getInstance().build(ARouterConfig.LaunchPage).navigation();
                break;
            case R.id.editUserInfoPage:
                ARouter.getInstance().build(ARouterConfig.EditUserInfoPage).navigation();
                break;
            case R.id.editUserNamePage:
                ARouter.getInstance().build(ARouterConfig.EditUserNamePage).navigation();
                break;
            case R.id.selectInterestPage:
                ARouter.getInstance().build(ARouterConfig.SelectInterestPage).navigation();
                break;
            case R.id.selectRegionPage:
                ARouter.getInstance().build(ARouterConfig.SelectRegionPage).navigation();
                break;
            case R.id.editUserBannerPage:
                ARouter.getInstance().build(ARouterConfig.EditUserBannerPage).navigation();
                break;
            case R.id.guaranteePage:
                ARouter.getInstance().build(ARouterConfig.GuaranteePage).navigation();
                break;
            case R.id.publishLearnVideoPage:
                ARouter.getInstance().build(ARouterConfig.PublishLearnVideoPage).navigation();
                break;
            case R.id.publishPhotoPage:
                ARouter.getInstance().build(ARouterConfig.PublishPhotoPage).navigation();
                break;
            case R.id.publishInfoPage:
                ARouter.getInstance().build(ARouterConfig.PublishInfoPage).navigation();
                break;
            case R.id.publishNormalVideoPage:
                ARouter.getInstance().build(ARouterConfig.PublishNormalVideoPage).navigation();
                break;
            case R.id.select_video:
                PictureSelector.create(this).openGallery(PictureMimeType.ofVideo())
                        .maxSelectNum(1).maxSize(Long.MAX_VALUE).forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
                break;
            case R.id.order_manager:
                OrderManagerPage.start();
                break;
            case R.id.merchandiseManagementPage:
                ARouter.getInstance().build(ARouterConfig.MerchandiseManagementPage).navigation();
                break;
            case R.id.my_orders:
                MyOrdersPage.start();
                break;
            case R.id.test_tra:
                String path = MyConfig.SDCARD_DIR + ((EditText) findViewById(R.id.video_name)).getText().toString();
                startTranscoder(path);
                break;
            case R.id.messageCenterPage:
                ARouter.getInstance().build(ARouterConfig.MessageCenterPage).navigation();
                break;
            case R.id.myFavorite:
                MyFavoritePage.start();
                break;
            case R.id.myView:
                MyViewsPage.start();
                break;
            case R.id.myBuy:
                MyBuyPage.start();
                break;
            case R.id.myUserPage:
                ARouter.getInstance()
                        .build(ARouterConfig.UserPage)
                        .withString("userId", AccountUtil.getCurrentUser().getId())
                        .navigation();
                break;
            case R.id.myDownloadPage:
                ARouter.getInstance()
                        .build(ARouterConfig.DownloadPage)
                        .navigation();
                break;
            case R.id.downloadBtn: {
                String goodsId;
                try {
                    goodsId = downloadGoodsIdEt.getText().toString().trim();
                } catch (Exception e) {
                    ToastX.show("goodsId不对");
                    return;
                }
                DownloadUtil.downloadVideo(this, goodsId,"","");
                break;
            }
            case R.id.publishMajorCourseDescBtn:
                ARouter.getInstance()
                        .build(ARouterConfig.PublishMajorCourseDescriptionPage)
                        .withParcelable("publishMajorCourseFormModel", MajorCourseFormModel.newBuilder().build())
                        .navigation();
                break;
            case R.id.publishMajorCourseFormBtn:
                ARouter.getInstance()
                        .build(ARouterConfig.PublishMajorCourseFormPage)
                        .withBoolean("edit", false)
                        .navigation();
                break;
            case R.id.wechatPay:
                ApiManager.getService()
                        .get(ApiUrls.BaseUrl + "eShop/orderPays/wechat?productId=asdgasdga&count=1")
                        .enqueue(new Callback<ResponseBody>() {
                            @Override
                            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                try {
                                    String payUrl = RetrofitUtil.getResponseBodyAsString(response);
                                    Map<String, Object> headers = new HashMap<>();
                                    headers.put("Referer", "http://test.dance365.com:8000");
                                    ARouter.getInstance()
                                            .build(ARouterConfig.WebViewPage)
                                            .withString("url", payUrl)
                                            .withObject("headers", headers)
                                            .withBoolean("disableNav", true)
                                            .navigation();
                                } catch (Exception e) {
                                    onFailure(call, e);
                                }
                            }

                            @Override
                            public void onFailure(Call<ResponseBody> call, Throwable t) {
                                ToastX.show(t.getMessage());
                            }
                        });
                break;
            case R.id.loadingDialogTest:
                new AsyncTask<Object, Object, Object>() {
                    LoadingDialog loadingDialog;

                    @Override
                    protected void onPreExecute() {
                        loadingDialog = LoadingDialog.newBuilder()
                                .with(DebugPage.this)
                                .show();
                    }

                    @Override
                    protected Object doInBackground(Object... objects) {
                        try {
                            Thread.sleep(1000);
                            return null;
                        } catch (InterruptedException e) {
                            return e;
                        }
                    }

                    @Override
                    protected void onPostExecute(Object o) {
                        loadingDialog.dismiss();
                        waiting = true;
                    }
                }.execute();
                break;
        }
    }

    boolean waiting = false;
    public ProgressDialog progressBar;

    @Override
    protected void onResume() {
        super.onResume();
        if (waiting) {
            Timber.e("onResume:true");
        } else {
            Timber.e("onResume:false");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                if (selectList != null && !selectList.isEmpty()) {
                    LocalMedia localMedia = selectList.get(0);
                    String videoPath = localMedia.getPath();
                    startTranscoder(videoPath);
                }
            }
        }
    }

    String videoInfo = "";
    long start;

    private void startTranscoder(final String videoPath) {
        final TranscoderUtils transcoderUtils = new TranscoderUtils();

        if (progressBar == null) {
            progressBar = new ProgressDialog(this);
        }
        videoInfo = "";
        start = System.currentTimeMillis();
        progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressBar.setTitle("FFmpeg4Android Direct JNI");
        progressBar.setMessage(videoPath);
        progressBar.setMax(100);
        progressBar.setProgress(0);
        progressBar.setCancelable(false);
        progressBar.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
//                transcoderUtils.exit();
                progressBar.dismiss();
            }
        });
        transcoderUtils.setCallback(new TranscoderUtils.TranscoderCallback() {
            @Override
            public void failed(String error) {
                ToastX.show(error);
                progressBar.cancel();
            }

            @Override
            public void cancel() {
                progressBar.cancel();
                ToastX.show("已取消");
            }

            @Override
            public void finish(String path) {
//                progressBar.cancel();
                ToastX.show("转码完成" + path);
                String avinfo = getOutVideoInfo(path);
                DebugPage.this.videoInfo = DebugPage.this.videoInfo + "\n" + avinfo
                        + "\n路径：" + path
                        + "\n转码花费时间：" + TimeUtils.stringForTime((System.currentTimeMillis() - start));
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        progressBar.setMessage(DebugPage.this.videoInfo);
                    }
                });

            }

            @Override
            public void progress(int progress) {
                Log.i("DebugPage", "progress:" + progress);
                progressBar.setProgress(progress);
            }

            @Override
            public void start(String videoInfo) {
                DebugPage.this.videoInfo = videoInfo;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        progressBar.setMessage(DebugPage.this.videoInfo);
                    }
                });

            }

        });
        transcoderUtils.start(videoPath);
        progressBar.show();
    }


    private String getOutVideoInfo(String path) {
        String avinfo = "";
        if (TextUtils.isEmpty(path)) {
            return null;
        }
        File file = new File(path);
        if (!file.exists()) {
            return null;
        }
        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        try {
            mmr.setDataSource(path);
            String title = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE); // api level 10, 即从GB2.3.3开始有此功能
            String duration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION); // 播放时长单位为毫秒
            String bitrate = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE); // 从api level 14才有，即从ICS4.0才有此功能
            String width = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);// 视频宽
            String height = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);// 视频高
            String framerate = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_CAPTURE_FRAMERATE);//帧率

            avinfo = "\n转码完成名称：" + file.getName()
                    + "\n分辨率:" + width + "x" + height
                    + "\n码率:" + (Long.parseLong(bitrate) / 1000) + "k"
                    + "\n时长:" + TimeUtils.stringForTime(Long.parseLong(duration))
                    + "\n大小:" + ((((double) file.length()) / 1024) / 1024) + "MB";

        } catch (IllegalArgumentException e) {
            e.printStackTrace();

        } catch (IllegalStateException e) {
            e.printStackTrace();

        }
        return avinfo;
    }

    public void gotoMyTest(View view) {
        startActivity(new Intent(this, TestQNPlayerPage.class));
    }

    public void gotoDetail1(View view) {
        ARouter.getInstance().build(ARouterConfig.DetailPage).withString("momentId", "ff8080816120cbd1016120cc7fca0002").navigation();
    }

    public void gotoDetail2(View view) {
        ARouter.getInstance().build(ARouterConfig.DetailPage).withString("momentId", "ff8080816120cbd1016120cd81e20003").navigation();
    }

    public void gotoDetail3(View view) {
        ARouter.getInstance().build(ARouterConfig.DetailPage).withString("momentId", "ff8080816120cbd1016120cc5ee50000").navigation();
    }


    public static void muxVideoAndAudio(String videoPath, String audioPath, String muxPath) {
        try {
            MediaExtractor videoExtractor = new MediaExtractor();
            videoExtractor.setDataSource(videoPath);
            MediaFormat videoFormat = null;
            int videoTrackIndex = -1;
            int videoTrackCount = videoExtractor.getTrackCount();
            for (int i = 0; i < videoTrackCount; i++) {
                videoFormat = videoExtractor.getTrackFormat(i);
                String mimeType = videoFormat.getString(MediaFormat.KEY_MIME);
                if (mimeType.startsWith("video/")) {
                    videoTrackIndex = i;
                    break;
                }
            }
            MediaExtractor audioExtractor = new MediaExtractor();
            audioExtractor.setDataSource(audioPath);
            MediaFormat audioFormat = null;
            int audioTrackIndex = -1;
            int audioTrackCount = audioExtractor.getTrackCount();
            for (int i = 0; i < audioTrackCount; i++) {
                audioFormat = audioExtractor.getTrackFormat(i);
                String mimeType = audioFormat.getString(MediaFormat.KEY_MIME);
                if (mimeType.startsWith("audio/")) {
                    audioTrackIndex = i;
                    break;
                }
            }
            videoExtractor.selectTrack(videoTrackIndex);
            audioExtractor.selectTrack(audioTrackIndex);
            MediaCodec.BufferInfo videoBufferInfo = new MediaCodec.BufferInfo();
            MediaCodec.BufferInfo audioBufferInfo = new MediaCodec.BufferInfo();
            MediaMuxer mediaMuxer = new MediaMuxer(muxPath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
            int writeVideoTrackIndex = mediaMuxer.addTrack(videoFormat);
            int writeAudioTrackIndex = mediaMuxer.addTrack(audioFormat);
            mediaMuxer.start();
            ByteBuffer byteBuffer = ByteBuffer.allocate(500 * 1024);
            long sampleTime = 0;
            {
                videoExtractor.readSampleData(byteBuffer, 0);
                if (videoExtractor.getSampleFlags() == MediaExtractor.SAMPLE_FLAG_SYNC) {
                    videoExtractor.advance();
                }
                videoExtractor.readSampleData(byteBuffer, 0);
                long secondTime = videoExtractor.getSampleTime();
                videoExtractor.advance();
                long thirdTime = videoExtractor.getSampleTime();
                sampleTime = Math.abs(thirdTime - secondTime);
            }
            videoExtractor.unselectTrack(videoTrackIndex);
            videoExtractor.selectTrack(videoTrackIndex);
            while (true) {
                int readVideoSampleSize = videoExtractor.readSampleData(byteBuffer, 0);
                if (readVideoSampleSize < 0) {
                    break;
                }
                videoBufferInfo.size = readVideoSampleSize;
                videoBufferInfo.presentationTimeUs += sampleTime;
                videoBufferInfo.offset = 0;
                //noinspection WrongConstant
                videoBufferInfo.flags = MediaCodec.BUFFER_FLAG_SYNC_FRAME;//videoExtractor.getSampleFlags()
                mediaMuxer.writeSampleData(writeVideoTrackIndex, byteBuffer, videoBufferInfo);
                videoExtractor.advance();
            }
            while (true) {
                int readAudioSampleSize = audioExtractor.readSampleData(byteBuffer, 0);
                if (readAudioSampleSize < 0) {
                    break;
                }
                audioBufferInfo.size = readAudioSampleSize;
                audioBufferInfo.presentationTimeUs += sampleTime;
                audioBufferInfo.offset = 0;
                //noinspection WrongConstant
                audioBufferInfo.flags = MediaCodec.BUFFER_FLAG_SYNC_FRAME;// videoExtractor.getSampleFlags()
                mediaMuxer.writeSampleData(writeAudioTrackIndex, byteBuffer, audioBufferInfo);
                audioExtractor.advance();
            }
            mediaMuxer.stop();
            mediaMuxer.release();
            videoExtractor.release();
            audioExtractor.release();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void mp3AndMp4(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    muxVideoAndAudio("/sdcard/test/stb1.mp4","/sdcard/test/adiao.mp3","/sdcard/test/adiao.mp4");
                } catch (Exception e) {
                    Log.v("XIACHAO","报错了:"+e.toString());
                }
            }
        }).start();
    }
}
